// button action start
function initButtons(obj) {
    bindSaveAction('#do_save',obj);
    bindSaveAction('#do_examine',obj);
    bindInvalidAction(obj);
    bindDeleteAction(obj);
    $('#to_list').click(function () {
        to_list(obj.htmlName);
    });
    $('#do_reset').click(function () {
        var hs = obj.htmlName.split('?');
        if( hs.length == 1 ){
            location.href = obj.htmlName  + '_add.html';    
        }else{
            location.href = hs[0]  + '_add.html?'+hs[1];
        }
        
    });
    $('#do_ext_dj').click(function () {
        if( params.code ){
            if( orderType == 1 ){
                var href = 'purchase/buy/buy_add?orderId='+params.id+'&orderCode='+params.code+'&thType=1&ot=1';
                top.menuClick({id:102,name:'采购单',href:href,center:true});
            }else if(orderType == 20){
                var href = 'market/sale/sale_add?orderId='+params.id+'&orderCode='+params.code+'&thType=1&ot=20';
                top.menuClick({id:202,name:'销售单',href:href,center:true});
            }
        }
    });
    $('#do_ext_tdj').click(function () {
        if( params.code ){
            if( orderType == 1 ){
                var href = 'purchase/rebuy/rebuy_add?orderId='+params.id+'&orderCode='+params.code+'&thType=1&ot=1';
                top.menuClick({id:103,name:'采购退货单',href:href,center:true});
            }else if(orderType == 20){
                var href = 'market/resale/resale_add?orderId='+params.id+'&orderCode='+params.code+'&thType=1&ot=20';
                top.menuClick({id:203,name:'销售退货单',href:href,center:true});
            }else if(orderType == 3){
                var href = 'purchase/rebuy/rebuy_add?orderId='+params.id+'&orderCode='+params.code+'&thType=2&ot=3';
                top.menuClick({id:103,name:'采购退货单',href:href,center:true});
            }else if(orderType == 22){
                var href = 'market/resale/resale_add?orderId='+params.id+'&orderCode='+params.code+'&thType=2&ot=22';
                top.menuClick({id:203,name:'销售退货单',href:href,center:true});
            }
        }
    });
}

function to_list(htmlName) {
    var hs = htmlName.split('?');
    if( hs.length == 1 ){
        location.href = htmlName + '_list.html?1=1'+app.setRequestParams(params);
    }else{
        location.href = hs[0] + '_list.html?'+hs[1]+app.setRequestParams(params);
    }
}

function init_edit_buttons(order,gridId) {
    if(order.status == 1){
        toSaveBtns();
    }else if(order.status > 1 && !params.ot){
        app.showExam(gridId);
        toExamineBtns(order);
    }
}

function bindDeleteAction(obj) {
    $('#do_remove').click(function(){
        layer.load();
        app.request({
            url:obj.service+'/delete',
            data:{id:params.id,orderId:params.orderId,orderCode:params.orderCode},
            success:function (resp) {
                layer.closeAll('loading');
                if( resp.result==0 ){
                    app.msg(layer,'操作成功',1);
                    to_list(obj.htmlName);
                }else{
                    app.msg(layer,'操作失败，请重试',2);
                }
            }
        });
    });
}

function bindInvalidAction(obj) {
    $('#do_invalid').click(function(){
        layer.load();
        app.request({
            url:obj.service+'/invalid',
            data:{id:params.id,orderType:obj.orderType,orderId:params.orderId,orderCode:params.orderCode},
            success:function (resp) {
                layer.closeAll('loading');
                if( resp.result==0 ){
                    app.msg(layer,'操作成功',1);
                    app.hideExam();
                    enablePageEdit();
                    toInvalidBtns();
                }else{
                    app.msg(layer,'操作失败【'+app.getErrorMessage(resp)+'】',2);
                }
            }
        });
    });
}

function bindSaveAction(query,obj) {
    $(query).click(function () {
        layer.load();
        editAfterEvent({target:{className:'before'}});
        if( !checkForm() ){
            layer.closeAll('loading');
            return;
        }
        var saveType = query == '#do_examine' ? 2 : 1;
        saveAction(saveType,obj);
    });
}

function doSave(url,data,saveType,obj){
    app.request({
        url:url,
        data:data,
        success:function(resp){
            var order = resp.data;
            if( resp.result==0 ){
                app.msg(layer,'操作成功',1);
                updateParams(order,obj);
                if(saveType==2){
                    app.showExam(obj.gridId);
                    disablePageEdit();
                    toExamineBtns(order,obj);
                }else{
                    oldData = data;
                    oldAccounts = accounts;
                    toSaveBtns();
                }
            }else{
                var message = top.bussError['code'+resp.data];
                if( message ){
                    app.msg(layer,'操作失败【'+message+'】',2);
                }else{
                    var gridId = obj.gridId ? obj.gridId : '#fixtable';
                    var rowData = $(gridId+' .ctx-left .vui-table-row').data();
                    if( rowData && rowData.product && rowData.product.id == resp.data ){
                        app.msg(layer,'操作失败【商品'+rowData.product.name+'已被删除】',2);
                    }
                }

            }
            layer.closeAll('loading');
        }
    });
}

var pageEdit = true;
function disablePageEdit() {
    pageEdit = false;
    $('#order_date').attr('disabled',true);
    $('input[name="order.realMoney"]').attr('disabled',true);
    $('input[name="order.discountMoney"]').attr('disabled',true);
    $('input[name="order.remarks"]').attr('disabled',true);
}

function enablePageEdit(){
    $('#order_date').attr('disabled',false);
    $('input[name="order.realMoney"]').attr('disabled',false);
    $('input[name="order.discountMoney"]').attr('disabled',false);
    $('input[name="order.remarks"]').attr('disabled',false);
    pageEdit = true;
}

function toSaveBtns() {
    app.shows(['#do_remove','#do_reset']);
}

function toExamineBtns(data) {
    var buttons = $('#do_save').parent();
    if( buttons.find('#do_print').length ==0 ){
        buttons.prepend('<button class="button hide" id="do_print"><span>打印</span></button>');
        $('#do_print').click(function () {

            var o = {loginUserId:top.loginUserId,customerId:top.customerId,loginCompanyId:top.loginCompanyId,loginCompanyLogicalCode:top.loginCompanyLogicalCode};
            var url = app.getBaseUrl()+"/html/system/print/print.html?id="+data.id+"&bussType="+orderType;
            for( var n in o ){
                url += "&"+n+"="+o[n];
            }
            url += '&loginName='+encodeURIComponent(top.loginName);
            url += '&loginCompanyName='+encodeURIComponent(top.loginCompanyName);

            window.open(url, "_blank");
        });
    }

    app.hides(['#do_save','#do_examine','#do_remove']);
    app.shows(['#do_invalid','#do_reset','#do_print']);
    if(data.bussType==1){
        app.shows(['#do_ext_dj']);
        app.hides(['#do_ext_tdj']);
    }else{
        app.shows(['#do_ext_tdj']);
        app.hides(['#do_ext_dj']);
    }
}

function toInvalidBtns() {
    app.shows(['#do_save','#do_examine','#do_remove']);
    app.hides(['#do_invalid','#do_ext_dj','#do_ext_tdj','#do_print']);
}

function updateParams(order,obj) {
    if(!params.id){
        params.id = order.id;
        params.code = order.code;
        params.status = order.status;
        params.orderType = obj.orderType;
        $('#order_title').html('编辑'+obj.orderText+'单 [ '+obj.codePrefix+order.code+' ]');
    }
}

//batchno
function batchNoSearchClick(searchId,gridId){
    var productId = $('#'+searchId).parent().parent().data().product.id;
    app.window(layer,{
        title:'批次号选择',
        area: ['620px', '600px'],
        content: '../../common/product_batch_list.html?searchId='+searchId+"&productId="+productId,
        end:function () {
            top.app.LAYUI_WINDOW_OPEND = false;
            //productSelected($('#'+searchId).parent(),gridId);
        }
    });
}

//product
function datagridSearchClick(searchId,gridId){
    app.window(layer,{
        title:'商品选择',
        btn:['选中','选中并关闭','取消'],
        yes: function(index, layero){
        },btn2: function(index, layero){
            return false;
        },btn3: function(index, layero){
            //按钮【按钮三】的回调
            //return false 开启该代码可禁止点击该按钮关闭
        },
        area: ['920px', '600px'],
        content: '../../common/product_list.html?searchId='+searchId,
        end:function () {
            top.app.LAYUI_WINDOW_OPEND = false;
            //productSelected($('#'+searchId).parent(),gridId);
        }
    });
}

function productSelectedCommon(cell,gridId) {
    gridId = gridId ? gridId : '#fixtable';
    var product = cell.data().product;
    var leftRow = cell.parent();
    var rowIndex = leftRow.attr('i');
    var rightRow = $(gridId+' .ctx-right .vui-table-row[i="'+rowIndex+'"]');

    cell.html(product.name);
    leftRow.data({product:product});
    rightRow.data({product:product});

    return {product:product,leftRow:leftRow,rightRow:rightRow};
}

function createRow(gridId,rows) {
    var conCreateRow = true;
    try{conCreateRow = backEditFlag;}catch(err){}

    if(conCreateRow){
        rows = rows ? rows : [{}];
        gridId = gridId ? gridId : '#fixtable';
        $(gridId).fixgrid('loadData',{rows:rows});
        refreshRowNumber(gridId);
    }
}

function removeRow(_this) {
    var row = _this.parent().parent().parent();
    var index = row.attr('i');
    var grid = row.parent().parent().parent();

    if( grid.find('.ctx-right .vui-table-row[bottom]').length > 0 ){
        if( grid.find('.ctx-right .vui-table-row[i="2"]').length == 0 ){
            return;
        }
    }else{
        if( grid.find('.ctx-right .vui-table-row[i="1"]').length == 0 ){
            return;
        }
    }

    row.remove();
    grid.find('.ctx-right .vui-table-row[i="'+index+'"]').remove();
    var gridId = '#'+grid[0].id;
    refreshRowNumber(gridId);
    //auto height
    $(gridId).height($(gridId).find('.top-left').height()+$(gridId).find('.ctx-right').height());
}

function refreshRowNumber(gridId) {
    gridId = gridId ? gridId : '#fixtable'; 
    $(gridId+' .ctx-left .vui-table-row').each(function (i,row) {
        $(row).attr('i',i);
        var bottom = $(row).attr('bottom');
        if( !bottom ){
            $(this).find('.vui-table-cell[field="serialnumber"]').html(i+1);
        }
    });
    $(gridId+' .ctx-right .vui-table-row').each(function (i,row) {
        $(row).attr('i',i);
    });
}

//操作列
function gridOpt(gridId){
    var addSpan = $('<span class="fix-table-icon"><i class="fa fa-plus  green"></i></span>');
    addSpan.click(function () {
        createRow(gridId);
    });
    var delSpan = $('<span class="fix-table-icon"><i class="fa fa-remove red"></i></span></div>');
    delSpan.click(function () {
        removeRow($(this));
    });
    var outDiv = $('<div></div>');
    outDiv.append(addSpan).append(delSpan);
    return outDiv;
}

function productEditBefore(cell) {
    var rowData = getRowDataByCell(cell);
    var grid = $(cell).parent().parent().parent().parent();
    if( grid.find('span[smqlr="u"]').attr('init') == 'on' ){
        var input = $('<input type="text" e="1" class="input-edit"/>');
        input.width(cell.width()-2);
        input.blur(function () {
            productEditBeforeEvent($(this));
        }).keydown(function(e){
            if( e.keyCode == 13 )productEditBeforeEvent($(this));
        });
        cell.empty();
        cell.append(input);
        input.focus();
        return false;
    }else{
        return true;    
    }

}

function productEditBeforeEvent(_input){
    var barcode = _input.val(),cell = _input.parent(),grid = $(cell).parent().parent().parent().parent();
    if( barcode != null && $.trim(barcode).length > 0 ){
       app.request({
           url:'product/getByBarcode',
           data:{barcode:barcode},
           success:function (resp) {
               if( resp.data && resp.data.id ){
                   cell.data({product:resp.data});
                   productSelected(cell,'#'+grid.attr('id'));
               }else{
                   
               }
           }
       }); 
    }else{
        var o = cell.data();
        if( o && o.product && o.product.id ){
            cell.empty();
            cell.html(o.product.name);
        }
    }
    
    
    _input.remove();
}

function editBefore(cell) {
    var field = cell.attr('field');
    if( !pageEdit ) return false;
    if( !backEditFlag && (field=='productId' || field=='storeId') ){
        return false;
    }

    if( cell.parent().attr('bottom') == '1')return false;
    if(field=='productId')return true;

    var rowData = getRowDataByCell(cell);
    if( !rowData || !rowData.product ){
        app.message(layer,'请先选择商品');
        return false;
    }
    return true;
}

function getRowDataByCell(cell) {
    var rightRow = cell.parent();
    var index = rightRow.attr('i');
    var rowData = rightRow.parent().parent().parent().find('.ctx-left .vui-table-row[i="'+index+'"]').data();
    return rowData;
}

function getRowEleProduct(that) {
    var cellData = that.find('.vui-table-cell[field="productId"]').data();
    return cellData.product;
}

function getField(bodyEle,field) {
    return bodyEle.find('.vui-table-cell[field="'+field+'"]');
}